<script setup lang="ts">
import { getUserInfo, upUserInfo, upUserPass } from "@/api/user/user";
import myCookies from "@/utils/myCookies";
import { ElMessage, ElMessageBox, type FormInstance, type UploadFile, type UploadFiles } from "element-plus";
interface User {
  nickname: string;
  avatar: string;
  mobile: number;
  gender: number;
  birthday: string;
  email: string;
}
const formPass=ref({
  oldPass: "",
  newPass: "",
  yesNewPass: "",
})
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请二次输入新密码'))
  } else if (value !== formPass.value.newPass) {
    callback(new Error("密码不一致"))
  } else {
    callback()
  }
}
const rules = {
  oldPass: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPass: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 18, message: '密码长度在6~18之间', trigger: 'blur' },
  ],  yesNewPass: [
    { required: true, validator:validatePass2, trigger: 'blur' },
    { min:  6, max: 18, message: '密码长度在6~18之间', trigger: 'blur' },
  ],}
const dialogVisible =ref(false)
import { reactive, ref, toRefs } from "vue";
const imageUrl = ref();
const loading = ref(false);
const ruleFormRef=ref()
//初始化
const loadUser = async () => {
  loading.value = true;
  await getUserInfo().then((response) => {
    imageUrl.value = response.data.data.avatar;
    form.value = response.data.data;
  });
  loading.value = false;
};

const data = reactive({
  form: <User>{},
});
const { form } = toRefs(data);
//图片上传成功回调
const handleAvatarSuccess = (
  response: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  imageUrl.value = response.data;
};
//提交
const submit = () => {
  ElMessageBox.confirm(
    '确定修改个人信息?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      form.value.avatar = imageUrl.value;
      await upUserInfo(form.value);
  //设置缓存用户信息
  await getUserInfo().then((response) => {
    localStorage.setItem("userInfo", JSON.stringify(response.data.data));
  });
      ElMessage({
        type: 'success',
        message: '修改个人信息成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消修改',
      })
    })
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await upUserPass(formPass.value).then(
        response=>{
          if(response.data.code ==200){
            ElMessage({
        type: 'success',
        message: response.data.msg,
      })
          }

        }
      )
      myCookies.removeToken()
      dialogVisible.value=false
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
// 禁用日期今天以后的
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now();
};
const beforeAvatarUpload = () => {};
loadUser();
</script>
<template>
  <el-form :model="form" class="user-info-box" label-position="top" v-loading="loading">
    <el-form-item>
      <el-upload
        class="avatar-uploader"
        action="/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <el-image v-if="imageUrl" :src="imageUrl" class="avatar" fit="fill" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>
    <el-divider />
    <el-row style="width: 500px">
      <el-col :span="12">
        <el-form-item label="昵称:" style="width: 240px">
          <el-input v-model="form.nickname" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="性别:" style="width: 240px">
          <el-select
            v-model="form.gender"
            a
            placeholder="选择你的性别"
            style="width: 240px"
          >
            <el-option
              v-for="item in [
                { value: 1, label: '男' },
                { value: 0, label: '女' },
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="生日:" style="width: 240px">
          <el-date-picker
            style="width: 240px"
            v-model="form.birthday"
            value-format="YYYY-MM-DD"
            range-separator="-"
            type="date"
            placeholder="选择你的出生日期"
            :disabled-date="disabledDate"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="手机号:" style="width: 240px">
          <el-input
            v-model="form.mobile"
            oninput="value=value.replace(/\D/g,'')"
            maxlength="11"
          /> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="邮箱:" style="width: 240px">
          <el-input v-model="form.email" /> </el-form-item
      ></el-col>
      <el-col :span="24">
        <el-button @click="submit">保存</el-button>
        <el-button @Click="dialogVisible = true">修改密码</el-button>
      </el-col>
    </el-row>
  </el-form>
  <el-dialog
    v-model="dialogVisible"
    title="修改账户密码"
    width="500"
    @close="resetForm(ruleFormRef)"
  >
    <el-form
      :model="formPass"
      :rules="rules"
      ref="ruleFormRef"
      label-position="top"
      status-icon
    >
      <el-form-item label="旧密码" prop="oldPass">
        <el-input v-model="formPass.oldPass" type="password" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPass">
        <el-input
          v-model="formPass.newPass"
          type="password"
          show-password
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="二次确认密码" prop="yesNewPass">
        <el-input
          v-model="formPass.yesNewPass"
          type="password"
          show-password
          autocomplete="off"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="less" scoped>
.user-info-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  .avatar-box {
    .avatar-uploader .avatar {
      width: 100px;
      height: 100px;
      border-radius: 100px;
      display: block;
    }
  }
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  width: 100px;
  height: 100px;
  border-radius: 100px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
